package com.itic.mall.system.productjd.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itic.appbase.applications.sys.syssetting.service.SysSettingService;
import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.RandomStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.UserSessionHelper;
import com.itic.mall.mobile.jd.MallJdUtils;
import com.itic.mall.system.productjd.persistence.model.ProductJd;
import com.itic.mall.system.productjd.persistence.model.ProductJdExample;
import com.itic.mall.system.productjd.persistence.model.ProductJdExample.Criteria;
import com.itic.mall.system.productjd.service.ProductJdService;

@Controller
@RequestMapping(value = "/system/productjd")
public class ProductJdController extends BaseController {
	@Autowired
	private ProductJdService productJdService;
	
	@Autowired
	private SysSettingService sysSettingService;

	////////////////////////////////////////////////////// 常量区////////////////////////////////////////////////////////////////
	private static final String MODEL_NAME_CHINA = "商品管理";// 中文名
	private static final String MODEL_NAME＿ENGLISH = "productjd";// 英文名
	private static final String PAGE_COMMON_PATH = "/mall/system/productjd/productjd";// 通用路径
	private static final String COMMON_URL = "/system/productjd/";// 通用路径

	////////////////////////////////////////////////////// 页面跳转区////////////////////////////////////////////////////////////

	/*
	 * 主页面
	 */
	@RequestMapping(value = "/init")
	public String init(Model model) {
		model.addAttribute("name_china", MODEL_NAME_CHINA);
		model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
		model.addAttribute("common_url", COMMON_URL);
		return PAGE_COMMON_PATH + "Main";
	}

	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/initOrder")
	public String initView(String id, Model model) {
		if (StringHelper.isNotBlank(id)) {

			ProductJd temp = productJdService.get(id);


			model.addAttribute("viewData", iticJsonMapper.toJson(temp));

			model.addAttribute("name_china", MODEL_NAME_CHINA);
			model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
			model.addAttribute("common_url", COMMON_URL);
		} else {
			throw new ParameterErrorException();
		}

		return PAGE_COMMON_PATH + "Order";
	}

	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/initBaokuan")
	public String initBaokuan(String id, Model model) {
		if (StringHelper.isNotBlank(id)) {

			ProductJd temp = productJdService.get(id);


			model.addAttribute("viewData", iticJsonMapper.toJson(temp));

			model.addAttribute("name_china", MODEL_NAME_CHINA);
			model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
			model.addAttribute("common_url", COMMON_URL);
		} else {
			throw new ParameterErrorException();
		}

		return PAGE_COMMON_PATH + "Baokuan";
	}

	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/initJingxuan")
	public String initJingxuan(String id, Model model) {
		if (StringHelper.isNotBlank(id)) {

			ProductJd temp = productJdService.get(id);


			model.addAttribute("viewData", iticJsonMapper.toJson(temp));

			model.addAttribute("name_china", MODEL_NAME_CHINA);
			model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
			model.addAttribute("common_url", COMMON_URL);
		} else {
			throw new ParameterErrorException();
		}

		return PAGE_COMMON_PATH + "Jingxuan";
	}
	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/initSeckill")
	public String initSeckill(String id, Model model) {
		if (StringHelper.isNotBlank(id)) {

			model.addAttribute("id", id);

			model.addAttribute("name_china", MODEL_NAME_CHINA);
			model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
			model.addAttribute("common_url", COMMON_URL);
		} else {
			throw new ParameterErrorException();
		}

		return PAGE_COMMON_PATH + "Jingxuan";
	}
	////////////////////////////////////////////////////// 业务代码区////////////////////////////////////////////////////////////


	/**
	 * <p>
	 * Title:queryCondition
	 * </p>
	 * <p>
	 * Description:封装查询条件
	 * </p>
	 * 
	 * @param jzdw
	 * @param jzdwExample
	 * @return
	 */
	private ProductJdExample queryCondition(HttpServletRequest request, ProductJd temp,String commType,String commTypePer, String createTimeType, String isCoupon ) {

		// 参数处理
		ProductJdExample example = new ProductJdExample();
		example.setOrderByClause("CREATE_TIME DESC");
		example.setOrderByClause("REORDER ASC");
		
		if( StringHelper.isNotBlank(commType) ){
			if( "001".equals(commType) ){
				example.setOrderByClause("COMMISSION_PROFIT DESC");
			}
			if( "002".equals(commType) ){
				example.setOrderByClause("COMMISSION_PROFIT ASC");
			}
		}
		
		if( StringHelper.isNotBlank(commTypePer) ){
			if( "001".equals(commTypePer) ){
				example.setOrderByClause("COMMISSION DESC");
			}
			if( "002".equals(commTypePer) ){
				example.setOrderByClause("COMMISSION ASC");
			}
		}
		
		if( StringHelper.isNotBlank(createTimeType) ){
			if( "001".equals(createTimeType) ){
				example.setOrderByClause("CREATE_TIME DESC");
			}
			if( "002".equals(createTimeType) ){
				example.setOrderByClause("CREATE_TIME ASC");
			}
		}

		
		com.itic.mall.system.productjd.persistence.model.ProductJdExample.Criteria criteria = example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);

		// 查询条件
		if (null != temp) {

			if (StringHelper.isNotBlank(temp.getGoodsName())) {
				criteria.andGoodsNameLike("%" + temp.getGoodsName() + "%");
			}
			
			if ( StringHelper.isNotBlank(temp.getIsBaokuan()) ){
				criteria.andIsBaokuanEqualTo(temp.getIsBaokuan());
			}
			if( StringHelper.isNotBlank(isCoupon) ){
				if( "001".equals(isCoupon) ){
					criteria.andConUrlBIsNotNull();
				}
				if( "002".equals(isCoupon) ){
					criteria.andConUrlBIsNull();
				}
			}
			
		}
		
		
		return example;
	}

	/**
	 * 
	 * @param goldType
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list( ProductJd tmp, HttpServletRequest request, String commType,String commTypePer,String createTimeType,String isCoupon) {
		// 声明返回对象
		Map<String, Object> resultMap = new HashMap<String, Object>();

		ProductJdExample example = this.queryCondition(request, tmp,commType,commTypePer,createTimeType,isCoupon);
		
		// 封装分页参数
		example = this.handlePageQuery(request, example);

		// 获取信息总条数
		int total = productJdService.count(example);

		// 获取数据
		List<ProductJd> list = productJdService.list(example);

		// 数据返回处理
		resultMap.put(IticConst.TOTAL_RECORDS, total);
		resultMap.put(IticConst.DISPLAY_RECORDS, total);
		resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
		resultMap.put(IticConst.DATA, list);
		return resultMap;

	}
	
	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/filterproduct")
	@ResponseBody
	public  Map<String, String> filterproduct() {
		 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SUCCESS.getCode();

         ProductJdExample example = new ProductJdExample();
     	 Criteria criteria = example.createCriteria();
     	 criteria.andIsEffectiveEqualTo(DBConst.TRUE);
     	 criteria.andConUrlBIsNotNull();
     	 
     	 List<ProductJd> list = productJdService.list(example);
     	 if( list.size()>0 ){
     		for( ProductJd temp: list ){
     			String convertResult = MallJdUtils.convert("0", temp.getSku(), temp.getConUrlB() );
     			if( StringHelper.isBlank(convertResult) ){
     				productJdService.delete(temp);
     			}
     		}
     	  }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
	}
	

	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/syncproduct")
	@ResponseBody
	public  Map<String, String> syncproduct() {
		 Map<String, String> resultMap = new HashMap<String, String>();

     	//deleteAll();
     	Integer total = 36000;//总数量30000条
     	//每次同步1条数据
     	for( int j=0;j<total;j++ ){
     		 JSONArray productList = MallJdUtils.queryProductList(j, 1);
     		 for (int i = 0; i < productList.size(); i++) {       	
     	            JSONObject p = productList.getJSONObject(i);

 	            	//判断数据库有没有这个数据
 	            	ProductJd jd = productJdService.getBySku(p.getString("sku"));
 	            	if( null == jd ){
 	            		ProductJd model = new ProductJd();
     	                model.setId(IdGen.uuid());
     	                ProductJdExample example = new ProductJdExample();
     	                example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
     	                int count = productJdService.count(example);
     	                model.setReorder(count+1);
     	                model.setCreateTime(new Date());
     	                model.setUpdateTime(new Date());
     	                model.setCreateUser(null != UserSessionHelper.get(Constants.USER_ID) ? UserSessionHelper.get(Constants.USER_ID) : "unknown");
     	                model.setOrgCode(null != UserSessionHelper.get(Constants.USER_ORG) ? UserSessionHelper.get(Constants.USER_ORG) : "unknown");
     	                model.setIsEffective(DBConst.TRUE);
     	                model.setProDesc(p.getString("proDesc"));
     	                model.setJdId(p.getString("jdId"));
     	                model.setCategoryName(p.getString("categoryName"));
     	                model.setGoodsInventory(p.getString("goodsInventory"));
     	                model.setParentId(p.getString("parentId"));
     	                model.setConExpireDate(p.getString("conExpireDate"));
     	                model.setOriPrice(p.getString("oriPrice"));
     	                model.setConUrl(p.getString("conUrl"));
      	                model.setGoodsUrl(p.getString("goodsUrl"));
     	                model.setConTicketPrice(p.getString("conTicketPrice"));
     	                
     	                model.setCompetitive(p.getString("competitive"));
     	                model.setRawId(p.getString("id"));
     	                model.setSku(p.getString("sku"));
     	                model.setConUrlB(p.getString("conUrlB"));
     	                model.setGoodsName(p.getString("goodsName"));
     	                model.setConPrice(p.getString("conPrice"));
     	                model.setTotalSales(RandomStringHelper.randomNumStr(4));
     	                
     	               /*if("1".equals(model.getCompetitive())){
	   	                	model.setIsBaokuan("001");
	   	                	ProductJdExample example2 = new ProductJdExample();
	       	                example2.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andIsBaokuanEqualTo("001");
	       	                int count2 = productJdService.count(example2);
	   	                	model.setOrderBaokuan(count2+1);
   	                   }*/
     	                
     	                /**
     	                 * 这是拿到手的佣金，京东还没有扣百分之十的
     	                 */
     	                //String subtractString = NumberStringHelper.subtractString(p.getString("conPrice"), p.getString("conTicketPrice"));
     	                String mulString = NumberStringHelper.mulString(p.getString("conPrice"), p.getString("commission"));
     	                String profit = NumberStringHelper.divString(mulString, "100", 2);
     	                
     	                String dianzhuCommission = getDianzhuCommission(profit);
     	                //佣金除以百分之
     	                model.setCommissionProfit(dianzhuCommission);
     	                String dianzhuCommissionPercent = getDianzhuCommissionProfit(dianzhuCommission,p.getString("oriPrice"));
     	                //计算店主的佣金 比
     	                model.setCommission(dianzhuCommissionPercent);
     	                
     	                productJdService.add(model);
     	                
     	                System.out.println("成功同步了京东商品"+model.getGoodsName());
 	            	}else{
 	            		//重新算一下店主和利润和百分比
 	            		/**
     	                 * 这是拿到手的佣金，京东还没有扣百分之十的
     	                 */
     	                //String subtractString = NumberStringHelper.subtractString(p.getString("conPrice"), p.getString("conTicketPrice"));
     	                String mulString = NumberStringHelper.mulString(p.getString("conPrice"), p.getString("commission"));
     	                String profit = NumberStringHelper.divString(mulString, "100", 2);
 	            		
 	            		String dianzhuCommission = getDianzhuCommission(profit);
 	            		String dianzhuCommissionPercent = getDianzhuCommissionProfit(dianzhuCommission,p.getString("conPrice"));
 	            		jd.setCommission(dianzhuCommissionPercent);
 	            		jd.setCommissionProfit(dianzhuCommission);
 	            		productJdService.edit(jd);
 	            	}
 	            
     	        }
     	 }
         
     
         resultMap.put(IticConst.RESULT, "success");
         return resultMap;
	}
	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/order")
	@ResponseBody
	public  Map<String, String> order(String id, Integer reorder) {
		 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         
         if ( StringHelper.isNotBlank(id) ) {
        	 ProductJd temp = productJdService.get(id);
        	 //temp.setReorder(reorder);
        	 //找到原来的排序，变成当前的
        	 ProductJdExample example = new ProductJdExample();
        	 example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andReorderEqualTo(reorder);
        	 List<ProductJd> list = productJdService.list(example);
        	 if( list.size() > 0 ){
        		 for( ProductJd tmp : list ){
        			 tmp.setReorder(temp.getReorder());
        			 productJdService.edit(tmp);
        		 }
        	 }
        	 temp.setReorder(reorder);
        	 result = productJdService.edit(temp);
         }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
	}
	
	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/baokuan")
	@ResponseBody
	public  Map<String, String> baokuan(String id, Integer orderBaokuan) {
		 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         
         if ( StringHelper.isNotBlank(id) ) {
        	 ProductJd temp = productJdService.get(id);
        	 //temp.setReorder(reorder);
        	 //找到原来的排序，变成当前的
        	 ProductJdExample example = new ProductJdExample();
        	 example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andOrderBaokuanEqualTo(orderBaokuan);
        	 List<ProductJd> list = productJdService.list(example);
        	 if( list.size() > 0 ){
        		 for( ProductJd tmp : list ){
        			 tmp.setOrderBaokuan(temp.getOrderBaokuan());
        			 productJdService.edit(tmp);
        		 }
        	 }
        	 temp.setIsBaokuan("001");
        	 temp.setOrderBaokuan(orderBaokuan);
        	 result = productJdService.edit(temp);
         }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
	}
	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/jingxuan")
	@ResponseBody
	public  Map<String, String> jingxuan(String id, Integer orderJingxuan) {
		 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         
         if ( StringHelper.isNotBlank(id) ) {
        	 ProductJd temp = productJdService.get(id);
        	 //temp.setReorder(reorder);
        	 //找到原来的排序，变成当前的
        	 ProductJdExample example = new ProductJdExample();
        	 example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andJingxuanOrderEqualTo(orderJingxuan);
        	 List<ProductJd> list = productJdService.list(example);
        	 if( list.size() > 0 ){
        		 for( ProductJd tmp : list ){
        			 tmp.setOrderBaokuan(temp.getOrderBaokuan());
        			 productJdService.edit(tmp);
        		 }
        	 }
        	 temp.setIsJingxuan("001");
        	 temp.setJingxuanOrder(orderJingxuan);
        	 result = productJdService.edit(temp);
         }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
	}
	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/delJingxuan")
	@ResponseBody
	public  Map<String, String> deljingxuan(String id) {
		 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         
         if ( StringHelper.isNotBlank(id) ) {
        	 ProductJd temp = productJdService.get(id);
        	 temp.setIsJingxuan("002");
        	 result = productJdService.edit(temp);
         }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
	}
	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/delBaokuan")
	@ResponseBody
	public  Map<String, String> delBaokuan(String id) {
		 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         
         if ( StringHelper.isNotBlank(id) ) {
        	 ProductJd temp = productJdService.get(id);
        	 temp.setIsBaokuan("002");
        	 result = productJdService.edit(temp);
         }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
	}
	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/seckill")
	@ResponseBody
	public  Map<String, String> seckill(ProductJd temp) {
		 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         
         if ( StringHelper.isNotBlank(temp.getId()) ) {
        	 result = productJdService.edit(temp);
         }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
	}
	
	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/delSeckill")
	@ResponseBody
	public  Map<String, String> delSeckill(String id) {
		 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         
         if ( StringHelper.isNotBlank(id) ) {
        	 ProductJd productJd = productJdService.get(id);
        	 productJd.setSeckillType("");
        	 result = productJdService.edit(productJd);
         }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
	}
	
	
	 /**
     * 计算店主的佣金
     * @return
     */
    public String getDianzhuCommission(String commission){
    	//京东扣除百分之十
    	String jdPercent="10";
    	String byKey = sysSettingService.getByKey("JD_MARKET_PROFIT_PERCENT");
    	if( StringHelper.isNotBlank(byKey) ){
    		jdPercent=byKey;
    	}
    	String divString = NumberStringHelper.divString(jdPercent, "100", 2);
    	String jdProfit = NumberStringHelper.mulString(commission, divString);//结算到京东的利润
    	
    	String backProfit = NumberStringHelper.subtractString(commission, jdProfit);//这是京东返回给我们的利润
    	
    	//与店主平分下利润
    	String ydProfit = NumberStringHelper.divString(backProfit, "2", 2);//这是给店主的利润
    	
    	return ydProfit;
    }
    
    /**
     * 计算店主的佣金百分比后多少金额
     * @return
     */
    public String getDianzhuCommissionProfit(String dianzhuCommission,String conPrice ){
    	String divString = NumberStringHelper.divString(dianzhuCommission, conPrice, 2);
    	String dianzhuPercent = NumberStringHelper.mulString(divString, "100");
    	return dianzhuPercent;
    }
    
    /*
	 * 查看页面
	 */
	@RequestMapping(value = "/del")
	@ResponseBody
	public  Map<String, String> del(String id) {
		 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         
         if ( StringHelper.isNotBlank(id) ) {
        	 ProductJd productJd = productJdService.get(id);
        	
        	 result = productJdService.delete(productJd);
         }
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
	}
	
	
}